﻿using System;
using System.ComponentModel;
using System.Data;
using org.se.fs.presenter.ITask.Profile;
using org.se.fs.presenter.Library;
using org.se.fs.presenter.Task.Template;

namespace org.se.fs.presenter.Task.Context
{
    public class Institution : Crud, IInstitution
    {
        public event FormEvent.FormEventHandler OnGetInstitutionActive;

        protected void TriggerGetInstitutionActive(FormEvent e)
        {
            if (OnGetInstitutionActive != null)
                OnGetInstitutionActive(this, e);
        }

        public void GetInstitutionActive()
        {
            using (var a = new BackgroundWorker())
            {
                a.DoWork += BgwGetInstitutionActiveDoWork;
                a.RunWorkerCompleted += BgwGetInstitutionActiveWorkerCompleted;
                a.RunWorkerAsync();
            }
        }

        #region Protected Backgroud Worker Function
        protected void BgwGetInstitutionActiveDoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                e.Result = new model.Table.Institution().GetInstitutionActive();
            }
            catch (Exception ex)
            {
                // Error Logs here
                e.Result = new DataTable();
                IsError = true;
                TriggerError(new FormEvent(true) { Exception = ex });
            }
        }

        protected void BgwGetInstitutionActiveWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            TriggerGetInstitutionActive(new FormEvent(!IsError) { Value = e.Result });
            IsError = false;
        }
        #endregion

        #region Protected Overridable Function
        protected override void BgwFetchDoWork(object sender, DoWorkEventArgs e)
        {                                                                                                                                                                                                                                                                                                                                                                                                   
        }

        protected override void BgFetchRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
        }

        protected override void BgwFetchListsDoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                e.Result = new model.Table.Institution().GetInstitutionLists();
            }
            catch (Exception ex)
            {
                // Error Logs here
                e.Result = new DataTable();
                IsError = true;
                TriggerError(new FormEvent(true) { Exception = ex });
            }   
        }

        protected override void BgFetchListsRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            TriggerFetchLists(new FormEvent(!IsError) { Value = e.Result });
            IsError = false;
        }

        protected override void BgwInsertDoWork(object sender, DoWorkEventArgs e)
        {
            var a = (DataTable)e.Argument;

            try
            {
                var name = a.Rows[0]["name"].ToString();
                var code = a.Rows[0]["code"].ToString();
                var branchId = Convert.ToUInt64(a.Rows[0]["branch_id"].ToString());
                var userCreateId = Convert.ToUInt64(a.Rows[0]["user_create_id"].ToString());
                var address = a.Rows[0]["address"].ToString();
                var contactEmail = a.Rows[0]["contact_email"].ToString();
                var contactMobileNum = a.Rows[0]["contact_mobile_num"].ToString();
                var contactName = a.Rows[0]["contact_name"].ToString();
                var contactPosition = a.Rows[0]["contact_position"].ToString();
                var contactTelNum = a.Rows[0]["contact_tel_num"].ToString();
                var faxNum = a.Rows[0]["fax_num"].ToString();
                var mobileNum = a.Rows[0]["mobile_num"].ToString();
                var telNum = a.Rows[0]["tel_num"].ToString();
                a.Rows[0]["id"] = new model.Table.Institution().Insert( name,  code,  branchId,  userCreateId,  address,  contactEmail,  contactMobileNum,  contactName,  contactPosition,  contactTelNum,  faxNum,  mobileNum,  telNum);
                
                if (!Convert.ToUInt64(a.Rows[0]["id"].ToString()).Equals(0))
                {
                    a.Rows[0]["created_date"] = DateTime.Now;
                    a.Rows[0]["is_active"] = true;
                }
                e.Result = a;
            }
            catch (Exception ex)
            {
                // Error Logs here
                a.Rows[0]["id"] = 0;
                e.Result = a;
                IsError = true;
                TriggerError(new FormEvent(true) { Exception = ex });
            }
        }

        protected override void BgInsertRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            var a = (DataTable)e.Result;
            var id = Convert.ToUInt64(a.Rows[0]["id"].ToString());
            TriggerInsert(new FormEvent(!id.Equals("0") && !IsError)
                              {
                                  Value = a,
                                  Exception = new Exception(id.Equals(0) ? "Insert failed." : "Insert success.")
                              });
            IsError = false;
        }

        protected override void BgwUpdateDoWork(object sender, DoWorkEventArgs e)
        {
            var a = (DataTable)e.Argument;
            try
            {
                var id = Convert.ToUInt64(a.Rows[0]["id"].ToString());
                var name = a.Rows[0]["name"].ToString();
                var code = a.Rows[0]["code"].ToString();
                var branchId = Convert.ToUInt64(a.Rows[0]["branch_id"].ToString());
                var userCreateId = Convert.ToUInt64(a.Rows[0]["user_create_id"].ToString());
                var address = a.Rows[0]["address"].ToString();
                var contactEmail = a.Rows[0]["contact_email"].ToString();
                var contactMobileNum = a.Rows[0]["contact_mobile_num"].ToString();
                var contactName = a.Rows[0]["contact_name"].ToString();
                var contactPosition = a.Rows[0]["contact_position"].ToString();
                var contactTelNum = a.Rows[0]["contact_tel_num"].ToString();
                var faxNum = a.Rows[0]["fax_num"].ToString();
                var mobileNum = a.Rows[0]["mobile_num"].ToString();
                var telNum = a.Rows[0]["tel_num"].ToString();
                IsSuccess = new model.Table.Institution().Update(id, name, code, branchId, userCreateId, address, contactEmail, contactMobileNum, contactName, contactPosition, contactTelNum, faxNum, mobileNum, telNum);
                e.Result = a;
            }
            catch (Exception ex)
            {
                // Error Logs here
                e.Result = a;
                IsSuccess = false;
                IsError = true;
                TriggerError(new FormEvent(true) { Exception = ex });
            }
        }

        protected override void BgUpdateRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            TriggerUpdate(new FormEvent(IsSuccess)
                              {
                                  Value = e.Result,
                                  Exception = new Exception(!IsSuccess ? "Update failed." : "Update success.")
                              });
        }

        protected override void BgwDeleteDoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                var a = (DataTable)e.Argument;
                IsSuccess = new model.Table.Institution().Delete(Convert.ToUInt64(a.Rows[0]["id"].ToString()));
                e.Result = a;
            }
            catch (Exception ex)
            {
                // Error Logs here
                e.Result = 0;
                IsError = true;
                TriggerError(new FormEvent(true) { Exception = ex });
            }      
        }

        protected override void BgDeleteRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            TriggerDelete(new FormEvent(IsSuccess && !IsError)
                              {
                                  Value = e.Result,
                                  Exception = new Exception(!IsSuccess ? "Update failed." : "Update success.")
                              });
            IsError = false;
        }

        protected override void BgwToggleDoWork(object sender, DoWorkEventArgs e)
        {
        }

        protected override void BgToggleRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
        }
        #endregion
    }
}
